package net.daum.webtoon.android.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import net.daum.webtoon.android.util.ImageDownloader.FlushedInputStream;
import net.daum.webtoon.android.util.ImageDownloader.Mode;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;

public class CacheUtil {

	private static final String TAG = CacheUtil.class.getSimpleName();

	private Context context;

	public CacheUtil(Context context) {
		this.context = context;
	}

	public void setImageByUrl(ImageView imageView, String url) {
		DownloadBitmapAsyncTask task = new DownloadBitmapAsyncTask(imageView);
		task.execute(url);
	}

	public Bitmap getImageFromUrl(String url) throws Exception {
		Bitmap bitmap = null;
		if (isExist(url) == false) {
			bitmap = downloadBitmap(url);
			setCacheBitmap(bitmap, url);
		} else {
			bitmap = getCacheBitmap(url);
			if (bitmap == null) {
				bitmap = downloadBitmap(url);
				setCacheBitmap(bitmap, url);
			}
		}
		return bitmap;
	}

	private File getImgFile(String url) {
		File dir = getCacheDir();
		String fileName = getUrlFromFileName(url);
		File img = new File(dir, fileName);
		return img;
	}

	private boolean isExist(String url) {
		return getImgFile(url).isFile();
	}

	private void setCacheBitmap(Bitmap bitmap, String url) throws IOException {
		OutputStream os = null;
		File img = getImgFile(url);

		try {
			os = new FileOutputStream(img);
			bitmap.compress(CompressFormat.JPEG, 70, os);
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	private Bitmap getCacheBitmap(String url) {
		Bitmap bitmap = null;
		File img = getImgFile(url);
		bitmap = BitmapFactory.decodeFile(img.toString());
		return bitmap;
	}

	private String getUrlFromFileName(String url) {
		String fileName = url.replace("http://", "");
		fileName = fileName.replace(".", "_");
		System.out.println(fileName.replaceAll("/", "_"));
		fileName += ".jpg";
		return fileName;
	}

	private File getCacheDir() {
		File dir = null;
		if (Constants.IS_EXTERNAL_CACHE_DIR) {
			String dirPath = Environment.getExternalStorageDirectory()
					.toString();
			dirPath += "/data/" + context.getPackageName() + "/cache";
			dir = new File(dirPath);
		} else {
			String dirPath = Environment.getDataDirectory().toString();
			dirPath += "/" + context.getPackageName() + "/cache";
			dir = new File(dirPath);
		}
		if (dir.isDirectory() == false) {
			dir.mkdirs();
		}
		return dir;
	}

	Bitmap downloadBitmap(String url) {

		// AndroidHttpClient is not allowed to be used from the main thread
		final HttpClient client = AndroidHttpClient.newInstance("Android");
		final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Logger.w("ImageDownloader", "Error " + statusCode
						+ " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					// return BitmapFactory.decodeStream(inputStream);
					// Bug on slow connections, fixed in future release.
					return BitmapFactory.decodeStream(new FlushedInputStream(
							inputStream));
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Logger.w(TAG, "I/O error while retrieving bitmap from " + url, e);
		} catch (IllegalStateException e) {
			getRequest.abort();
			Logger.w(TAG, "Incorrect URL: " + url, e);
		} catch (Exception e) {
			getRequest.abort();
			Logger.w(TAG, "Error while retrieving bitmap from " + url, e);
		} finally {
			if ((client instanceof AndroidHttpClient)) {
				((AndroidHttpClient) client).close();
			}
		}
		return null;
	}

	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	private class DownloadBitmapAsyncTask extends
			AsyncTask<String, Void, Bitmap> {

		ImageView imageView;

		public DownloadBitmapAsyncTask(ImageView imageView) {
			this.imageView = imageView;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap b = null;
			try {
				b = getImageFromUrl(params[0]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return b;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result != null) {
				imageView.setImageBitmap(result);
			}
		}

	}

}
